using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using Services.Initial.PublicProject.PublicClasses.Error;
using Services.Initial.PublicProject.PublicClass.ExtensionException;
using Services.Initial.PublicProject.PublicMethods;
using Services.Initial.PublicProject.PublicTopic;
using SimpleRabbitmq;

namespace Services.InitialProject.Filters;
public class ExceptionFilter : IAsyncExceptionFilter
{
    private readonly ILogger<ExceptionFilter> logger;
    private readonly IEventBus eventBus;
    public ExceptionFilter(IEventBus eventBus, ILogger<ExceptionFilter> logger)
    {
        this.eventBus = eventBus;
        this.logger = logger;
    }

    /// <summary>
    /// 注册全局异常处理器
    /// </summary>
    /// <param name="context"></param>
    /// <returns></returns>
    public Task OnExceptionAsync(ExceptionContext context)
    {
        context.ExceptionHandled = true;
        this.logger.LogInterpolatedInformation($"{context.Exception.Message}");
        if (context.Exception is ExceptionWithStatus myException)
        {
            //this.eventBus.Publish(nameof(ErrorEunm.Exception), new TransferError(context.Exception.Message, context.Exception.StackTrace!, DateTime.Now));
            context.Result = new JsonResult(OutPutMethod<string>.Failure(message: myException.Message, statusCode: (int)myException.HttpStatusCode, data: ""));
        }
        else
        {
            this.eventBus.PublishAsync(ExceptionTopic.UnExpectedTopic, new TransferError(context.Exception.Message, context.Exception.StackTrace!, DateTime.Now));
            context.Result = new JsonResult(OutPutMethod<string>.Failure(message: "程序出现未可预见的异常，请联系管理人员，稍后再试", data: ""));
        }
        return Task.CompletedTask;
    }
}